package com.hwpt.hwaccount.feature.auth.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.hwpt.hwaccount.R;
import com.hwpt.hwaccount.core.data.UserTableObserver;
import com.hwpt.hwaccount.feature.auth.AuthContract;
import com.hwpt.hwaccount.feature.auth.AuthModel;
import com.hwpt.hwaccount.feature.auth.AuthPresenter;
import com.hwpt.hwaccount.feature.home.HomeActivity;

public class AuthActivity extends AppCompatActivity implements AuthContract.View {

    private TextView tvLoginTab, tvRegisterTab, tvSwitchLoginType, tvForgetPassword, tvPrivacy, tvEmailTip, tvSkip;
    private View viewIndicator;
    private LinearLayout llLoginForm, llRegisterForm, llSetPasswordForm, llVerifyCodeLogin, llPasswordLogin;
    private TextInputLayout tilLoginAccount, tilRegisterPhone;
    private TextInputEditText etLoginAccount, etVerifyCode, etPassword, etRegisterPhone, etRegisterVerifyCode, etSetPassword, etConfirmPassword;
    private Button btnGetVerifyCode, btnRegisterGetVerifyCode, btnLogin, btnNextStep, btnRegister;
    private CountDownTimer countDownTimer;
    private AuthContract.Presenter presenter;
    private TextView tvDisplayPhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auth);

        initViews();
        setupListeners();

        AuthContract.Model model = new AuthModel(this);
        presenter = new AuthPresenter(model);
        presenter.attachView(this);
    }

    private void initViews() {
        tvLoginTab = findViewById(R.id.tv_login_tab);
        tvRegisterTab = findViewById(R.id.tv_register_tab);
        viewIndicator = findViewById(R.id.view_indicator);

        tvSwitchLoginType = findViewById(R.id.tv_switch_login_type);
        tvForgetPassword = findViewById(R.id.tv_forget_password);
        tvPrivacy = findViewById(R.id.tv_privacy);
        tvEmailTip = findViewById(R.id.tv_email_tip);
        tvSkip = findViewById(R.id.tv_skip);

        llLoginForm = findViewById(R.id.ll_login_form);
        llRegisterForm = findViewById(R.id.ll_register_form);
        llSetPasswordForm = findViewById(R.id.ll_set_password_form);
        llVerifyCodeLogin = findViewById(R.id.ll_verify_code_login);
        llPasswordLogin = findViewById(R.id.ll_password_login);

        tilLoginAccount = findViewById(R.id.til_login_account);
        etLoginAccount = findViewById(R.id.et_login_account);
        etVerifyCode = findViewById(R.id.et_verify_code);
        etPassword = findViewById(R.id.et_password);
        btnGetVerifyCode = findViewById(R.id.btn_get_verify_code);

        tilRegisterPhone = findViewById(R.id.til_register_phone);
        etRegisterPhone = findViewById(R.id.et_register_phone);
        etRegisterVerifyCode = findViewById(R.id.et_register_verify_code);
        btnRegisterGetVerifyCode = findViewById(R.id.btn_register_get_verify_code);
        etSetPassword = findViewById(R.id.et_set_password);
        etConfirmPassword = findViewById(R.id.et_confirm_password);
        tvDisplayPhone = findViewById(R.id.tv_display_phone);

        btnLogin = findViewById(R.id.btn_login);
        btnNextStep = findViewById(R.id.btn_next_step);
        btnRegister = findViewById(R.id.btn_register);
    }

    private void setupListeners() {
        tvLoginTab.setOnClickListener(v -> presenter.onTabSelected(true));
        tvRegisterTab.setOnClickListener(v -> presenter.onTabSelected(false));

        tvSwitchLoginType.setOnClickListener(v -> presenter.onSwitchLoginType());
        tvForgetPassword.setOnClickListener(v -> presenter.onForgetPassword());
        tvPrivacy.setOnClickListener(v -> presenter.onPrivacyClicked());
        tvSkip.setOnClickListener(v -> presenter.onSkipClicked());

        btnGetVerifyCode.setOnClickListener(v -> presenter.onGetVerifyCode(btnGetVerifyCode));
        btnRegisterGetVerifyCode.setOnClickListener(v -> presenter.onGetVerifyCode(btnRegisterGetVerifyCode));

        btnLogin.setOnClickListener(v -> presenter.onLogin());
        btnNextStep.setOnClickListener(v -> presenter.RegisterVerifyCode());
        btnRegister.setOnClickListener(v -> presenter.onRegister());
    }

    @Override
    public void switchTab(boolean isLogin) {
        if (isLogin) {
            // 显示登录表单
            llLoginForm.setVisibility(View.VISIBLE);
            llRegisterForm.setVisibility(View.GONE);
            llSetPasswordForm.setVisibility(View.GONE);
            btnLogin.setVisibility(View.VISIBLE);

            // 清除注册相关的输入框
            clearRegisterInputs();

        } else {
            // 显示注册表单（只显示第一步）
            llLoginForm.setVisibility(View.GONE);
            llRegisterForm.setVisibility(View.VISIBLE);
            llSetPasswordForm.setVisibility(View.GONE);
            btnLogin.setVisibility(View.GONE);

            // 确保注册状态重置为第一步
            if (presenter != null) {
                presenter.resetRegisterState();
                updateRegisterFormUI();
            }
        }
    }

    // 新增方法：清除注册输入框
    private void clearRegisterInputs() {
        etRegisterPhone.setText("");
        etRegisterVerifyCode.setText("");
        etSetPassword.setText("");
        etConfirmPassword.setText("");
        tvDisplayPhone.setText("");
        tilRegisterPhone.setError(null);
    }

    //显示手机号
    @Override
    public void displayRegisterPhone(String phone) {
        if (tvDisplayPhone != null) {
            tvDisplayPhone.setText(phone);
        }
    }

    @Override
    public void updateTabUI() {
        if (presenter.isLoginTabSelected()) {
            tvLoginTab.setTextColor(getResources().getColor(android.R.color.holo_blue_light));
            tvRegisterTab.setTextColor(getResources().getColor(android.R.color.darker_gray));

            viewIndicator.post(() -> {
                int loginTabWidth = tvLoginTab.getWidth();
                int loginTabLeft = tvLoginTab.getLeft();
                viewIndicator.setX(loginTabLeft);
                viewIndicator.getLayoutParams().width = loginTabWidth;
                viewIndicator.requestLayout();
            });
        } else {
            tvLoginTab.setTextColor(getResources().getColor(android.R.color.darker_gray));
            tvRegisterTab.setTextColor(getResources().getColor(android.R.color.holo_blue_light));

            viewIndicator.post(() -> {
                int registerTabWidth = tvRegisterTab.getWidth();
                int registerTabLeft = tvRegisterTab.getLeft();
                viewIndicator.setX(registerTabLeft);
                viewIndicator.getLayoutParams().width = registerTabWidth;
                viewIndicator.requestLayout();
            });
        }
    }

    @Override
    public void updateLoginTypeUI() {
        if (presenter.isVerifyCodeLogin()) {
            llVerifyCodeLogin.setVisibility(View.VISIBLE);
            llPasswordLogin.setVisibility(View.GONE);
            tvSwitchLoginType.setText("密码登录");
            tilLoginAccount.setHint("手机号/邮件地址");
            tvEmailTip.setVisibility(View.GONE);
        } else {
            llVerifyCodeLogin.setVisibility(View.GONE);
            llPasswordLogin.setVisibility(View.VISIBLE);
            tvSwitchLoginType.setText("验证码登录");
            tilLoginAccount.setHint("账号");
            String account = etLoginAccount.getText().toString().trim();
            tvEmailTip.setVisibility(account.contains("@") ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void updateRegisterFormUI() {
        if (presenter.isRegisterFirstStep()) {
            llRegisterForm.setVisibility(View.VISIBLE);
            llSetPasswordForm.setVisibility(View.GONE);
            // 清除第二步的表单数据
            etSetPassword.setText("");
            etConfirmPassword.setText("");
        } else {
            llRegisterForm.setVisibility(View.GONE);
            llSetPasswordForm.setVisibility(View.VISIBLE);
            // 确保显示正确的手机号
            String phone = etRegisterPhone.getText().toString().trim();
            tvDisplayPhone.setText(phone);
        }
    }

    @Override
    public void startCountDown(Button button, long millisUntilFinished) {
        button.setEnabled(false); //立即禁用按钮
        countDownTimer = new CountDownTimer(millisUntilFinished, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                button.setText(String.format("%ds后重新获取", millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                resetButton(button);
            }
        }.start();
    }

    @Override
    public void resetButton(Button button) {
        button.setEnabled(true);
        button.setText("获取验证码");
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    public void showToast(String message) {
        runOnUiThread(() -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
    }

    @Override
    public void navigateToRepwdActivity() {
        startActivity(new Intent(this, RepwdActivity.class));
    }

    @Override
    public void navigateToHomeActivity() {
        startActivity(new Intent(this, HomeActivity.class));

        // 启动用户表监听
        UserTableObserver observer = UserTableObserver.getInstance(this);
        if (!observer.isObserving()) {
            observer.startObserving();
        }
        finish();
    }

    @Override
    public void finishActivity() {
        finish();
    }

    @Override
    public void showPhoneError(String error) {
        tilRegisterPhone.setError(error);
    }

    @Override
    public void showAccountError(String error) {
        tilLoginAccount.setError(error);
    }

    @Override
    public String getLoginAccount() {
        return etLoginAccount.getText().toString().trim();
    }

    @Override
    public String getVerifyCode() {
        return etVerifyCode.getText().toString().trim();
    }

    @Override
    public String getPassword() {
        return etPassword.getText().toString().trim();
    }

    @Override
    public String getRegisterPhone() {
        return etRegisterPhone.getText().toString().trim();
    }

    @Override
    public String getRegisterVerifyCode() {
        return etRegisterVerifyCode.getText().toString().trim();
    }

    @Override
    public String getSetPassword() {
        return etSetPassword.getText().toString().trim();
    }

    @Override
    public String getConfirmPassword() {
        return etConfirmPassword.getText().toString().trim();
    }

    @Override
    public Button getRegisterVerifyCodeButton() {
        return btnRegisterGetVerifyCode;
    }


    @Override
    public void showError(String message) {
        showToast(message);
    }

    @Override
    public void showSuccess(String message) {
        showToast(message);
    }

    @Override
    protected void onDestroy() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        if (presenter != null) {
            presenter.detachView();
            presenter.onDestroy();
        }
        super.onDestroy();
    }

    @Override
    public void setLoginAccount(String account) {
        runOnUiThread(() -> {
            etLoginAccount.setText(account);
        });
    }
}